package multithread;

/**
 * Created by xiebang
 * Description
 * User:小谢
 * Date:2021-12-01
 * Time:17:25
 */
public class ThreadDemo1 {
    private static  long count = 100_0000_0000L;
    //针对整数进行大量的循环相加
    public static void main(String[] args) {
        serial();
        concurrency();
    }

    private static void concurrency() {
        long begin = System.currentTimeMillis();
        //通过匿名内部类的方式继承Thread
        Thread t1 = new Thread(){
            @Override
            public void run(){
                int a = 0;
                for (long i = 0; i < count; i++) {
                    a++;
                }
            }

        };
        Thread t2 = new Thread(){
            @Override
            public void run() {
                int b = 0;
                for (long i = 0; i < count; i++) {
                    b++;
                }
            }
        };
        t1.start();
        t2.start();
        //t1.t2与main线程之间都是并发执行的
        //调用了t1.start与t2.start之后,两个新线程正在紧锣密鼓的进行计算过程中,
        //此时主线程任然会继续执行,下面的end就随后被计算了
        //正确的做法应该是保证t1和t2计算完成,在来计算end的时间戳

        //代码模板 主流的开发工具都有这个功能
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long end = System.currentTimeMillis();

        System.out.println("time: " + (end - begin) + "ms");
    }

    private static void serial() {
        long begin = System.currentTimeMillis();
        int a = 0;
        for (long i = 0; i < count; i++) {
            a++;
        }
        int b = 0;
        for (long i = 0; i < count; i++) {
            b++;
        }

        long end = System.currentTimeMillis();
        System.out.println("time: " + (end - begin) + "ms");
        //
    }
}
